# src/api/collection_api.py
from flask import Blueprint, request, jsonify
from src.service.collection_service import (
    add_artwork_to_collection,
    remove_artwork_from_collection,
    get_user_collection_list
)
from src.utils.logger import get_logger

collection_bp = Blueprint("collection", __name__, url_prefix="/api/collection")
logger = get_logger(__name__)

@collection_bp.route("/add", methods=["POST"])
def add():
    """添加艺术品到收藏"""
    try:
        data = request.get_json()
        user_id = data.get("user_id")
        artwork_id = data.get("artwork_id")
        
        success, msg = add_artwork_to_collection(user_id=user_id, artwork_id=artwork_id)
        
        if success:
            return jsonify({"success": True, "message": msg}), 200
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"添加收藏接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@collection_bp.route("/remove", methods=["POST"])
def remove():
    """从收藏中移除艺术品"""
    try:
        data = request.get_json()
        user_id = data.get("user_id")
        artwork_id = data.get("artwork_id")
        
        success, msg = remove_artwork_from_collection(user_id=user_id, artwork_id=artwork_id)
        
        if success:
            return jsonify({"success": True, "message": msg}), 200
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"移除收藏接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@collection_bp.route("/user/<int:user_id>", methods=["GET"])
def get_user_collections(user_id):
    """获取用户收藏列表"""
    try:
        collections, msg = get_user_collection_list(user_id=user_id)
        
        return jsonify({
            "success": True,
            "count": len(collections),
            "collections": collections
        }), 200
    except Exception as e:
        logger.error(f"获取收藏列表接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500